
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Fixed;     use Ada.Strings.Fixed;

-- https://leetcode.com/problems/reverse-integer
procedure leet7_reverseint is
    -- reverse is a reserved word; can't be an identifier
    function reverseint (a : in Integer) return Integer is
        buffer : Unbounded_String;
        x : Integer := abs(a);
        t : Integer;
        y : Integer;
    begin
        if x > 0 and x < 10 then -- single digit
            return x;
        else 
            while x > 0 loop
                t := x rem 10;
                append(buffer, trim(Integer'image(t), left));
                x := (x - t)/10;
            end loop;
        end if;
        if a < 0 then
            buffer := '-' & buffer;
        end if;
        begin
            y := Integer'value(to_string(buffer));
        exception
            when CONSTRAINT_ERROR =>
                return 0;
        end;
        return y;
    end reverseint;

    input  : Integer;
    result : Integer;
begin 
    if argument_count < 1 then
        put_line("This is leetcode algorithm challenge #7 - Reverse Integer");
        put_line("usage: <program name> <integer>");
        return;
    end if;
    input := Integer'value(argument(1));
    result := reverseint(input);
    put_line(Integer'image(result));
end leet7_reverseint;
